<template>
	<view>
		<uni-forms ref="ruleForm" :form-rules="rules" @submit="submitForm">
			<uni-field name="title" label="标题" placeholder="请输入标题" v-model="formData.title"></uni-field>
			<uni-field name="content" label="内容" maxlength="-1" type="textarea" placeholder="请输入内容" v-model="formData.content"></uni-field>
			<view class="button-group">
				<button form-type="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import db from '@/js_sdk/uni-clientDB/index.js';
	const dbCmd = db.command;
	export default {
		data() {
			return {
				// 直接通过属性传入组件内可能方法无法传递，需要手动调用一个初始化校验规则函数
				formData: {
					title: '',
					content: ''
				},
				rules: {
					"title": [{
						"required": true,
						message: "标题不能为空",
						trigger: 'blur'
					}, {
						minLength: 2,
						maxLength: 20,
						message: "标题长度需在{minLength}-{maxLength}之间",
						trigger: 'blur'
					}],
					"content": [{
						"required": true,
						message: "内容不能为空",
						trigger: 'blur'
					}, {
						minLength: 10,
						maxLength: 14000,
						message: "内容长度需在{minLength}-{maxLength}之间",
						trigger: 'blur'
					}]
				}
			}
		},
		onLoad() {},
		methods: {
			submitForm(event) {
				const {
					value,
					errors
				} = event.detail
				if (errors) {
					return
				}
				this.requestForm(value)
			},
			requestForm(data) {
				uni.showLoading({
					title: '发布中'
				})

				db.action('publish')
					.collection('opendb-news-articles')
					.add(data)
					.then((res) => {
						if (res.result.code) {
							uni.showModal({
								content: res.result.message,
								showCancel: false
							})
							return
						}
						console.log(res)
						uni.showModal({
							content: '发布成功',
							showCancel: false
						})
					}).catch((err) => {
						console.error(err)
						uni.showModal({
							content: '发布失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
			}
		}
	}
</script>

<style>
</style>
